let dao = require('../database/dao'),
  logger = require('../helper/logger'),
  tagLogger = new logger.TagLogger('USER_MODEL'),
  errorCode = require('../../conf/errorCode'),
  commonModel = require('./commonModel'),
  util = require('../helper/util'),
  _ = require('lodash');

let {
  genUpdateCallback,
  genInsertCallback,
  genUpdateRslt,
  genUpdateBatchRslt,
  genUpdateBatchCallback,
  genSelectCallback,
  genPagination,
  genInertRslt,
} = commonModel;

exports.getByAccountName = function(accountName, page, size, callback) {
  let [offset, limit] = util.ps2ol(page, size),
    fromJoinWhere = `FROM user where accountName like '%${accountName}%'`;
  //fromJoinWhere = `FROM user`;
  let postQuery = {
    str: `SELECT * ${fromJoinWhere} LIMIT ?,?`,
    param: [offset, limit],
  };
  let countQuery = {
    str: `SELECT count(1) as count ${fromJoinWhere}`,
    param: [],
  };
  let queryArr = [postQuery, countQuery];
  dao.queryBatch(queryArr, (err, rslts) => {
    if (err == null)
      callback(null, genPagination(rslts[0], page, size, rslts[1][0].count));
    else callback(err, null);
  });
};

exports.blockUserByIds = function(userId, callback) {
  dao.updateByIds('user', userId, {status: 1}, callback);
};

exports.getUserInfo = function(userId, callback) {
  dao.all(
    `select id userId,accountName userName,avatarUrl,role from user where id=?`,
    [userId],
    (err, rslts) => {
      if (err == null) callback(null, rslts);
      else callback(err, null);
    },
  );
};
exports.getUserListByNamePrefix = function(namePrefix, callback) {
  let fromJoinWhere = `FROM user where accountName like '${namePrefix}%'`;
  dao.all(
    `SELECT id,accountName,mobile ${fromJoinWhere} LIMIT 0,10`,
    [],
    (err, rslts) => {
      if (err == null) callback(null, rslts);
      else callback(err, null);
    },
  );
};

//获取用户列表
exports.getUserByPage = function(namePrefix, page, size, callback) {
  let [offset, limit] = util.ps2ol(page, size),
    fromJoinWhere = `FROM user as u where accountName like '${namePrefix}%'`;

  let postQuery = {
    str: `SELECT u.id uid, u.accountName userName,u.status,u.avatarUrl avatarUrl,u.createdAt createTime,u.mobile,u.role ${fromJoinWhere} order by u.createdAt desc LIMIT ?,? `,
    param: [offset, limit],
  };
  let countQuery = {
    str: `SELECT count(1) as count ${fromJoinWhere}`,
    param: [],
  };
  let queryArr = [postQuery, countQuery];
  dao.queryBatch(queryArr, (err, rslts) => {
    if (err == null)
      callback(null, genPagination(rslts[0], page, size, rslts[1][0].count));
    else callback(err, null);
  });
};

//修改用户角色
exports.modifyUserRole = (uid, role, callback) => {
  dao.all(`update user set role = ? where id=?`, [role, uid], callback);
};
